/* 
 * Quick anti-aliased text scroller for Peggy 2
 * uses subset of Liberation Sans Narrow font
 *
 * If you're running low on program space you could compress 
 * the font, it's quite inefficiently wasting 6 bits per byte.
 *
 * awescroller
 * Copyright  (C) 2011 Mark J Cox <mark@awe.com>
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <Peggy2.h>
#include "parsefont.h"

Peggy2 frame4;
Peggy2 frame2;
Peggy2 frame1;
   
void set_pixel(byte x, byte y, byte bright)
{
    frame4.WritePoint(x,y,(bright&4));
    frame2.WritePoint(x,y,(bright&2));
    frame1.WritePoint(x,y,(bright&1));
}
 
void refresh_display(byte repeat) 
{
    for (byte i=0; i<repeat; i++) {
        frame4.RefreshAll(4);
        frame2.RefreshAll(2);
        frame1.RefreshAll(1);
    }
}
 
void setup()
{
     frame4.HardwareInit();
     DDRB = 0xFE; // port b pin 0 input
     PORTB |= 0x01; // pull up
     DDRC = 0xE0;
     PORTC |= 0x1F;
}

char text[]="HAPPY HALLOWEEN..... BOO!   ";
unsigned short text_ptr = 0;
unsigned short xcurrent = 0;
unsigned short xlast = -2;
unsigned short speed = 5;

void loop() 
{ 
  if (!(PINB & 0x1)) { // select: pause
   refresh_display(50);
   return;
  }
  if (!(PINC & 0x04)) { // up: faster
    speed ++;
    refresh_display(50);
  } else if (!(PINC & 0x08)) { // down: slower
    speed --;
    refresh_display(50);
  }
  
  // Scroll everything left one position
  for (byte i = 0; i<24; i++) {
         frame4.buffer[i]=frame4.buffer[i]>>1;
         frame2.buffer[i]=frame2.buffer[i]>>1;
         frame1.buffer[i]=frame1.buffer[i]>>1;
  }
  if (xcurrent-1 > xlast) {  // new character needed
     unsigned char xch = text[text_ptr];
     if (xch == 0) {  // end of text, move back to start
       text_ptr = 0;
       xch = text[0];
     }
     text_ptr++;
     xcurrent = cs[(unsigned short)xch - 32]; // offset start and end into font data
     xlast = cl[(unsigned short)xch - 32];        
  } 
  if (xcurrent-1 != xlast) {  // one blank column after each char
      for (byte i = 0; i<chars_height; i++) {
          set_pixel(24,20-i,pgm_read_byte_near(chars+xcurrent*chars_height+i));
      }
  }
  xcurrent++;
  refresh_display(speed);
}
